<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ page import="Servlets.qy.StockQueryServlet" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/pages/stock_manage/";
%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <base href="<%= basePath %>"/>
    <title>库存查询</title>
    <style>
        body {
            margin: 0;
            font-family: 'Segoe UI', 'Arial', sans-serif;
            background: #f5f6fa;
        }

        .header {
            background: #4f8cff;
            color: #fff;
            padding: 24px 0 18px 0;
            text-align: center;
            font-size: 2rem;
            font-weight: bold;
            letter-spacing: 2px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        }

        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .filter-form {
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        .filter-form label {
            margin-right: 5px;
            font-weight: 500;
            color: #333;
        }

        .filter-form input, .filter-form select {
            padding: 10px 12px;
            border: 1px solid #dcdde1;
            border-radius: 6px;
            margin-right: 10px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .filter-form input:focus, .filter-form select:focus {
            outline: none;
            border-color: #4f8cff;
            box-shadow: 0 0 0 2px rgba(79, 140, 255, 0.2);
        }

        .filter-form input[type="submit"] {
            background-color: #4f8cff;
            color: white;
            border: none;
            cursor: pointer;
            font-weight: 500;
            padding: 10px 20px;
            transition: background-color 0.3s;
        }

        .filter-form input[type="submit"]:hover {
            background-color: #3a7bff;
        }

        /* 固定下拉框宽度 */
        .category-select {
            width: 160px;
            box-sizing: border-box;
        }

        .product-list {
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        .product-list th, .product-list td {
            border: 1px solid #eee;
            padding: 14px 12px;
            text-align: left;
            word-wrap: break-word;
        }

        .product-list th {
            background-color: #f8f9fc;
            font-weight: 600;
            color: #4a5568;
            text-transform: uppercase;
            font-size: 13px;
            letter-spacing: 0.5px;
        }

        .product-list tbody tr {
            transition: background-color 0.2s;
        }

        .product-list tbody tr:hover {
            background-color: #f8faff;
        }

        /* 为每列设置固定宽度 */
        .product-list .name-col {
            width: 25%;
        }

        .product-list .category-col {
            width: 20%;
        }

        .product-list .origin-col {
            width: 20%;
        }

        .product-list .quantity-col {
            width: 15%;
        }

        .product-list .action-col {
            width: 20%;
        }

        .action-col button {
            background-color: #4f8cff;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            transition: background-color 0.2s;
        }

        .action-col button:hover {
            background-color: #3a7bff;
        }

        .detail-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(2px);
            animation: fadeIn 0.3s ease-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        .detail-content {
            background-color: #fff;
            margin: 10% auto;
            padding: 30px;
            border-radius: 8px;
            width: 80%;
            max-width: 500px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-60px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            line-height: 1;
            cursor: pointer;
            transition: color 0.2s;
        }

        .close:hover,
        .close:focus {
            color: #333;
        }

        .detail-content h2 {
            margin-top: 0;
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 15px;
            text-align: center;
        }

        .detail-table {
            width: 100%;
            border-collapse: collapse;
        }

        .detail-table th, .detail-table td {
            padding: 10px;
            border-bottom: 1px solid #eee;
        }

        .detail-table th {
            text-align: left;
            font-weight: 600;
            color: #4a5568;
            width: 30%;
        }

        .detail-table td {
            color: #2d3748;
        }

        /* 查询结果为空时的样式 */
        .no-results {
            text-align: center;
            padding: 40px;
            color: #718096;
            font-size: 16px;
        }

        .no-results:before {
            content: "😔";
            display: block;
            font-size: 48px;
            margin-bottom: 15px;
        }

        /* 美化分页样式 */
        .pagination-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 25px;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        .pagination-info {
            color: #4a5568;
            font-size: 14px;
        }

        .pagination {
            display: flex;
            align-items: center;
            list-style: none;
        }

        .pagination li {
            margin: 0 3px;
        }

        .pagination a, .pagination span {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            border-radius: 6px;
            text-decoration: none;
            color: #4a5568;
            font-weight: 500;
            transition: all 0.2s ease-in-out;
            border: 1px solid transparent;
        }

        .pagination a:hover {
            background-color: #edf2f7;
            color: #4f8cff;
        }

        .pagination .active span {
            background-color: #4f8cff;
            color: white;
            border-color: #4f8cff;
        }

        .pagination .disabled a {
            color: #cbd5e0;
            cursor: not-allowed;
        }

        .pagination .disabled a:hover {
            background-color: transparent;
            color: #cbd5e0;
        }

        .pagination .prev-next a {
            width: auto;
            padding: 0 14px;
        }

        .pagination .prev-next a:hover {
            background-color: #edf2f7;
        }

        .pagination .prev-next.active a {
            background-color: #4f8cff;
            color: white;
        }

        .pagination .prev-next.active a:hover {
            background-color: #3a7bff;
        }

        .pagination-jump {
            display: flex;
            align-items: center;
            color: #4a5568;
            font-size: 14px;
        }

        .pagination-jump input {
            width: 50px;
            padding: 8px;
            margin: 0 8px;
            border: 1px solid #dcdde1;
            border-radius: 4px;
            text-align: center;
            transition: border-color 0.3s;
        }

        .pagination-jump input:focus {
            outline: none;
            border-color: #4f8cff;
            box-shadow: 0 0 0 2px rgba(79, 140, 255, 0.2);
        }

        .pagination-jump button {
            padding: 8px 14px;
            background-color: #4f8cff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.2s;
            margin-left: 8px;
        }

        .pagination-jump button:hover {
            background-color: #3a7bff;
        }

        .loading {
            text-align: center;
            padding: 20px;
        }

        .loading:after {
            content: " ";
            display: inline-block;
            width: 20px;
            height: 20px;
            margin: 0 10px;
            border-radius: 50%;
            border: 3px solid #4f8cff;
            border-color: #4f8cff transparent #4f8cff transparent;
            animation: loading 1.2s linear infinite;
        }

        @keyframes loading {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        .hidden {
            display: none;
        }
    </style>
    <script src="${pageContext.request.contextPath}/webjars/jquery/3.6.0/jquery.min.js"></script>

    <script>
        // 分页相关的变量
        var currentPage = 1;
        var pageSize = 5;
        var totalPage = 1;
        var totalCount = 0;

        function openDetailModal(productId) {
            // 显示模态框
            document.getElementById('detailModal').style.display = 'flex';

            // 显示加载状态
            document.getElementById('modalContent').innerHTML = '<div class="loading"></div>';

            // 使用 AJAX 调用后端接口获取详细信息
            $.ajax({
                url: "StockQueryServlet",
                method: 'GET',
                data: {
                    action: 'getProductDetail',
                    productId: productId
                },
                dataType: 'json',
                success: function (response) {
                    var modalContent = document.getElementById('modalContent');

                    // 检查响应是否成功
                    if (response) {
                        var product = response.data.results[0];

                        console.log(product);
                        console.log(product.proname);
                        // 使用字符串拼接方式构建详细信息
                        var html =
                            '<h2 class="detail-title">商品详细信息</h2>' +
                            '<table class="detail-table">' +
                            '<tr>' +
                            '<td>商品名称</td>' +
                            '<td>' + (product.proname || '-') + '</td>' +
                            '</tr>' +
                            '<tr>' +
                            '<td>价格(元/斤)</td>' +
                            '<td>' + (product.price ? '¥' + product.price : '-') + '</td>' +
                            '</tr>' +
                            '<tr>' +
                            '<td>原产地</td>' +
                            '<td>' + (product.originplace || '-') + '</td>' +
                            '</tr>' +
                            '<tr>' +
                            '<td>品质等级</td>' +
                            '<td>' + (product.levelname || '-') + '</td>' +
                            '</tr>' +
                            '<tr>' +
                            '<td>生产年份</td>' +
                            '<td>' + (product.productionyear || '-') +"年"+
                            (product.productionmonth || '-') +"月"+ '</td>' +
                            '</tr>' +
                            '</table>';

                        console.log(html);
                        modalContent.innerHTML = html;
                    } else {
                        modalContent.innerHTML = '<span class="close" onclick="closeDetailModal()">&times;</span>' +
                            '<h2 class="detail-title">商品详细信息</h2>' +
                            '<div class="no-results">暂无详细信息</div>';
                    }
                },
                error: function (error) {
                    console.error('获取商品详情失败:', error);
                    document.getElementById('modalContent').innerHTML = '<span class="close" onclick="closeDetailModal()">&times;</span>' +
                        '<h2 class="detail-title">商品详细信息</h2>' +
                        '<div class="no-results">获取信息失败</div>';
                }
            });
        }


        function closeDetailModal() {
            // 隐藏模态框
            document.getElementById('detailModal').style.display = 'none';
            // 清空模态框内容
            document.getElementById('modalContent').innerHTML = '';
        }

        // 页面加载完成后动态加载分类数据
        window.onload = function () {
            loadCategories();
            loadProducts("", "");
        }

        // 从后端获取茶叶分类数据并填充到下拉框
        function loadCategories() {
            // 显示加载状态
            var categorySelect = document.getElementById("category");
            categorySelect.innerHTML = '<option value="">加载中...</option>';

            $.ajax({
                url: "StockQueryServlet",
                method: 'GET',
                data: {
                    action: 'getCategories'
                },
                dataType: 'json',
                success: function (categories) {
                    // 清空现有选项（除了"全部"）
                    categorySelect.innerHTML = '<option value="">全部</option>';

                    // 添加从数据库获取的分类选项
                    if (categories && categories.length > 0) {
                        categories.forEach(function (category) {
                            var option = document.createElement("option");
                            option.value = category.id;
                            option.text = category.name;
                            categorySelect.appendChild(option);
                        });
                    }
                },
                error: function (error) {
                    console.error('获取分类数据失败:', error);
                    categorySelect.innerHTML = '<option value="">全部</option>';
                }
            });
        }

        // 处理表单提交
        function submitForm(event) {
            event.preventDefault(); // 阻止表单默认提交行为

            var productName = document.getElementById("productName").value;
            var category = document.getElementById("category").value;
            currentPage = 1; // 重置为第一页
            loadProducts(productName, category);
        }

        function loadProducts(productName, category) {
            // 显示加载状态
            var tbody = document.querySelector("#productList tbody");
            tbody.innerHTML = '<tr><td colspan="5" class="loading"></td></tr>';

            $.ajax({
                url: "StockQueryServlet",
                method: 'POST',
                data: {
                    action: 'search',
                    productName: productName,
                    category: category,
                    currentPage: currentPage,
                    pageSize: pageSize
                },
                dataType: 'json',
                success: function (response) {
                    try {

                        var data = response.data || {};
                        var products = data.results || [];
                        totalCount = data.totalCount || 0;
                        totalPage = data.totalPage || 1;

                        // 显示产品列表
                        displayProducts(products);

                        // 更新分页控件
                        updatePagination();
                    } catch (e) {
                        console.error("处理数据出错:", e);
                        tbody.innerHTML = '<tr><td colspan="5" class="no-results">数据加载失败</td></tr>';
                    }
                },
                error: function (error) {
                    console.error("获取商品数据失败:", error);
                    tbody.innerHTML = '<tr><td colspan="5" class="no-results">获取数据失败，请稍后重试</td></tr>';
                }
            });
        }

        // 显示产品列表
        function displayProducts(products) {
            var tbody = document.querySelector("#productList tbody");
            tbody.innerHTML = ""; // 清空现有内容

            if (!products || products.length === 0) {
                var row = tbody.insertRow();
                var cell = row.insertCell(0);
                cell.colSpan = 5;
                cell.textContent = "没有找到匹配的商品";
                cell.className = "no-results";
                return;
            }

            products.forEach(function (product) {
                var row = tbody.insertRow();

                var nameCell = row.insertCell(0);
                nameCell.textContent = product.proname || '-';
                nameCell.className = "name-col";

                var categoryCell = row.insertCell(1);
                categoryCell.textContent = product.categoryname || '-';
                categoryCell.className = "category-col";

                var originCell = row.insertCell(2);
                originCell.textContent = product.originplace || '-';
                originCell.className = "origin-col";

                var quantityCell = row.insertCell(3);
                quantityCell.textContent = product.quantity || '0';
                quantityCell.className = "quantity-col";

                var actionCell = row.insertCell(4);
                actionCell.className = "action-col";
                var button = document.createElement("button");
                button.textContent = "详情";
                button.onclick = function () {
                    openDetailModal(product.id);
                };
                actionCell.appendChild(button);
            });
        }

        // 更新分页控件
        function updatePagination() {
            // 更新分页信息
            document.querySelector(".pagination-info").textContent =
                "共" + totalCount + "条记录,当前第" + currentPage + "/" + totalPage + "页";
            // 更新分页按钮
            updatePaginationButtons();

            // 更新跳转输入框
            var jumpInput = document.querySelector(".pagination-jump input");
            jumpInput.max = totalPage;
            jumpInput.value = currentPage;
        }

        // 更新分页按钮
        function updatePaginationButtons() {
            var paginationUl = document.querySelector(".pagination");
            paginationUl.innerHTML = "";

            // 上一页
            var prevLi = document.createElement("li");
            prevLi.className = "prev-next " + (currentPage <= 1 ? "disabled" : "");
            var prevLink = document.createElement("a");
            prevLink.href = "#";
            prevLink.innerHTML = "&laquo; 上一页";
            prevLink.onclick = function (e) {
                e.preventDefault();
                if (currentPage > 1) {
                    currentPage--;
                    var productName = document.getElementById("productName").value;
                    var category = document.getElementById("category").value;
                    loadProducts(productName, category);
                }
            };
            prevLi.appendChild(prevLink);
            paginationUl.appendChild(prevLi);

            // 页码
            var startPage = Math.max(1, currentPage - 2);
            var endPage = Math.min(totalPage, currentPage + 2);

            // 确保显示5个页码按钮
            if (endPage - startPage < 4) {
                if (startPage === 1) {
                    endPage = Math.min(totalPage, startPage + 4);
                } else {
                    startPage = Math.max(1, endPage - 4);
                }
            }

            // 第一页
            if (startPage > 1) {
                var firstLi = document.createElement("li");
                var firstLink = document.createElement("a");
                firstLink.href = "#";
                firstLink.textContent = "1";
                firstLink.onclick = function (e) {
                    e.preventDefault();
                    currentPage = 1;
                    var productName = document.getElementById("productName").value;
                    var category = document.getElementById("category").value;
                    loadProducts(productName, category);
                };
                firstLi.appendChild(firstLink);
                paginationUl.appendChild(firstLi);

                // 省略号
                if (startPage > 2) {
                    var ellipsisLi = document.createElement("li");
                    ellipsisLi.textContent = "...";
                    paginationUl.appendChild(ellipsisLi);
                }
            }

            // 中间页码
            for (var i = startPage; i <= endPage; i++) {
                var pageLi = document.createElement("li");
                if (i === currentPage) {
                    pageLi.className = "active";
                    var pageSpan = document.createElement("span");
                    pageSpan.textContent = i;
                    pageLi.appendChild(pageSpan);
                } else {
                    var pageLink = document.createElement("a");
                    pageLink.href = "#";
                    pageLink.textContent = i;
                    pageLink.onclick = (function (page) {
                        return function (e) {
                            e.preventDefault();
                            currentPage = page;
                            var productName = document.getElementById("productName").value;
                            var category = document.getElementById("category").value;
                            loadProducts(productName, category);
                        };
                    })(i);
                    pageLi.appendChild(pageLink);
                }
                paginationUl.appendChild(pageLi);
            }

            // 最后一页
            if (endPage < totalPage) {
                // 省略号
                if (endPage < totalPage - 1) {
                    var ellipsisLi = document.createElement("li");
                    ellipsisLi.textContent = "...";
                    paginationUl.appendChild(ellipsisLi);
                }

                var lastLi = document.createElement("li");
                var lastLink = document.createElement("a");
                lastLink.href = "#";
                lastLink.textContent = totalPage;
                lastLink.onclick = function (e) {
                    e.preventDefault();
                    currentPage = totalPage;
                    var productName = document.getElementById("productName").value;
                    var category = document.getElementById("category").value;
                    loadProducts(productName, category);
                };
                lastLi.appendChild(lastLink);
                paginationUl.appendChild(lastLi);
            }

            // 下一页
            var nextLi = document.createElement("li");
            nextLi.className = "prev-next " + (currentPage >= totalPage ? "disabled" : "");
            var nextLink = document.createElement("a");
            nextLink.href = "#";
            nextLink.innerHTML = "下一页 &raquo;";
            nextLink.onclick = function (e) {
                e.preventDefault();
                if (currentPage < totalPage) {
                    currentPage++;
                    var productName = document.getElementById("productName").value;
                    var category = document.getElementById("category").value;
                    loadProducts(productName, category);
                }
            };
            nextLi.appendChild(nextLink);
            paginationUl.appendChild(nextLi);
        }

        // 跳转到指定页
        function jumpToPage() {
            var jumpInput = document.querySelector(".pagination-jump input");
            var page = parseInt(jumpInput.value);
            if (page >= 1 && page <= totalPage) {
                currentPage = page;
                var productName = document.getElementById("productName").value;
                var category = document.getElementById("category").value;
                loadProducts(productName, category);
            } else {
                alert(`请输入有效的页码 (1-${totalPage})`);
                jumpInput.focus();
            }
        }

        // 绑定回车事件
        document.addEventListener('DOMContentLoaded', function () {
            var jumpInput = document.querySelector(".pagination-jump input");
            jumpInput.addEventListener('keyup', function (e) {
                if (e.key === 'Enter') {
                    jumpToPage();
                }
            });
        });
    </script>
</head>
<body>

<div class="header">库存查询</div>

<div class="container">
    <!-- 筛选条件区域 -->
    <form class="filter-form" onsubmit="submitForm(event)">
        <label for="productName">商品名称：</label>
        <input type="text" id="productName" name="productName" placeholder="输入商品名称">

        <label for="category">分类：</label>
        <select id="category" name="category" class="category-select">
            <option value="">全部</option>
        </select>

        <input type="submit" value="查询">
    </form>

    <!-- 商品库存列表 -->
    <table class="product-list" id="productList">
        <thead>
        <tr>
            <th class="name-col">商品名称</th>
            <th class="category-col">茶叶类型</th>
            <th class="origin-col">原产地</th>
            <th class="quantity-col">库存数量</th>
            <th class="action-col">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td colspan="5" class="loading"></td>
        </tr>
        </tbody>
    </table>

    <!-- 分页控件 -->
    <div class="pagination-wrapper">
        <div class="pagination-info">共 0 条记录，当前第 1/1 页</div>
        <ul class="pagination">
            <li class="prev-next disabled"><a href="#">&laquo; 上一页</a></li>
            <li class="active"><span>1</span></li>
            <li class="prev-next disabled"><a href="#">下一页 &raquo;</a></li>
        </ul>
        <div class="pagination-jump">
            跳转到 <input type="number" min="1" max="1" value="1"> 页
            <button onclick="jumpToPage()">确定</button>
        </div>
    </div>
</div>

<!-- 库存详情弹窗 -->
<div id="detailModal" class="detail-modal">
    <div class="detail-content">
        <span class="close" onclick="closeDetailModal()">&times;</span>
        <div id="modalContent">
            <!-- 动态加载详细信息 -->
        </div>
    </div>
</div>

</body>
</html>